package api

import (
	"fmt"
	"gitee.com/cdsailyj/go-vpn/common/core"
	"gitee.com/cdsailyj/go-vpn/common/tool"
	"gitee.com/cdsailyj/go-vpn/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Vpn struct {
	core.Api
}

func (i Vpn) List(c *gin.Context) {
	for _, v := range robotService.Clients {
		if len(v.LastFrame) > 0 {
			imgBytes, err := tool.ResizeImg(v.LastFrame, 80, 320, 180)
			if err != nil {
				continue
			}
			s := tool.Base64Encode(imgBytes)
			v.LastFrameBase64 = s
			v.CmdChanLength = len(v.CmdChan)
		}
	}
	c.JSON(http.StatusOK, gin.H{"code": 0, "data": robotService.Clients})
}

func (i Vpn) Sync(c *gin.Context) {
	var client service.VpnClient
	if err := c.ShouldBindJSON(&client); err != nil {
		i.Error(c, 1, "参数验证失败:"+err.Error())
		return
	}
	vpnFind := robotService.Clients[client.UserId]
	if vpnFind == nil {
		vpnFind = service.NewVpnClient(client.UserId)
	}

	fmt.Printf("收到同步客户端： %#v \n", client.UserId)
	vpnFind.ControlFlag = client.ControlFlag
	vpnFind.ControlBy = client.ControlBy
	vpnFind.Online = client.Online
	vpnFind.DisplayNum = client.DisplayNum
	vpnFind.DisplayCurrent = client.DisplayCurrent
	vpnFind.Screens = client.Screens
	vpnFind.Ip = client.Ip
	vpnFind.FPS = client.FPS
	vpnFind.Quality = client.Quality
	if len(client.LastFrameBase64) > 0 {
		vpnFind.LastFrameBase64 = client.LastFrameBase64
	}

	i.Success(c, gin.H{"code": 0, "data": robotService.Clients})
}

// 停止本机视频共享和远程控制
func (i Vpn) StopVPN(c *gin.Context) {
	robotService.MyClient.Stop()
	c.JSON(http.StatusOK, gin.H{"code": 0})
}

// 初始化本地客户端
func (i Vpn) StartVPN(c *gin.Context) {
	set, _ := SettingService.GetSetting()
	if len(set.UserId) == 0 {
		i.Error(c, 1, "用户ID未配置，请前往系统设置")
		return
	}
	robotService.InitMyClient()
	c.JSON(http.StatusOK, gin.H{"code": 0, "data": robotService.MyClient})
}
